package com.zl.roomdesign

import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import com.zl.core.MainApp
import com.zl.core.base.BaseActivity
import com.zl.core.db.AppDatabase
import com.zl.core.extend.toTextString
import com.zl.core.utils.SPUtils
import com.zl.roomdesign.auth.LoginActivity
import com.zl.roomdesign.main.MainActivity
import kotlin.concurrent.thread

class SplashActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        val host = SPUtils.getString(SPUtils.HOST)
        if (host == null) {
            inputIP()
        } else {
            if (checkIP(host)) {
                MainApp.instance.serverUrl = "http://$host/"
                next()
            } else {
                inputIP()
            }
        }
    }

    private fun inputIP() {
        val view = EditText(this)
        view.hint = "192.168.1.1"
        AlertDialog.Builder(this)
                .setTitle("设置服务器IP和端口")
                .setView(view)
                .setPositiveButton("确定", { _, _ ->
                    val ip = view.toTextString()
                    if (checkIP(ip)) {
                        MainApp.instance.serverUrl = "http://$ip/"
                        SPUtils.saveString(SPUtils.HOST, ip)
                        next()
                    } else {
                        showToastSafe("IP和端口的格式类似: 192.168.1.101:8080")
                        inputIP()
                    }
                })
                .show()
    }

    private fun next() {
        val phone = SPUtils.getString(SPUtils.PHONE, null)?.toLongOrNull()
        if (phone != null) {
            thread {
                val user = AppDatabase.getInstance().userDao().getUserByPhone(phone)
                MainApp.instance.user = user
                runOnUiThread {
                    if (user != null) {
                        startActivity(Intent(this, MainActivity::class.java))
                        finish()
                    } else {
                        startActivity(Intent(this, LoginActivity::class.java))
                        finish()
                    }
                }
            }
        } else {
            startActivity(Intent(this, LoginActivity::class.java))
            finish()
        }
    }

    private fun checkIP(ipAndPort: String): Boolean {
        val ip = Regex("([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}")
        val split = ipAndPort.split(Regex(":"))
        if (split.size == 2) {
            if (split[0].matches(ip)) {
                val port = split[1].toIntOrNull()
                if (port != null && port > 0 && port < 65535) {
                    return true
                }
            }
        }
        return false
    }


}
